
import i18n from '@src/locales';
import { getCountries, getAreaDivisionsInfo } from '@src/api/Address';

import { getAddressData } from 'pub-bbx-utils';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

// 通过省市区的key获取省市区的name
function getAreaName(value = {}, areaList = []) {
    const { province, city, dist} = getAddressData(value);
    const areaArr = [ province, city, dist ].filter( item => !!item)  

    if(!areaArr.length) return [];
    
    return keyToName(areaArr,areaList)
}

// 通过省市区key数组转换成省市区name数组
function keyToName(areaKeyArr,areaList) {

    let dist = areaList

    let name = []
    for(let key of areaKeyArr){

        const findItem = dist.find(item => {
            if(key === item.key){
                return item
            }
        })
        findItem && (name.push(findItem.name));
        dist = findItem.dist;
    }

    return name
}

// 获取国家列表
async function getInternationalCountries(){
    const { status, data } = await getCountries();

    return data || []
}

// 获取指定国家的所有省市区数据
async function getArea(divisionKey){
    const { data } = await getAreaDivisionsInfo({divisionKey})

    return data?.dist || []
}

// 是否需要将value里面的国家省市区字段转为当前系统语言对应的国家省市区字段
export function isTranslation(){
    return internationalGray && i18n?.locale !== 'zh'
}

// 获取国家的key
export function getCountryKey(addressObj){
    let key = '';
    const {country, province} = getAddressData(addressObj);

    if(country) key = country;
    // 默认中国，保存到数据库就是中文的，'中国‘不需要多语言!!!!!!!!!!!!!'中国‘不需要多语言!!!!!!!!!!!!!'中国‘不需要多语言!!!!!!!!!!!!!
    if(province && !country) key = '中国';

    return key;
}

export default async function addressKeyToViewLanguage (countryKey,addressObj){
    // 当不需要转换时，直接返回原数据
    if(!isTranslation() || !countryKey){
        return addressObj;
    }

    const areaList = await getArea(countryKey);
    const countryList = await getInternationalCountries();
    const names = getAreaName(addressObj,areaList);

    const country = countryList.find( item => {
        return item.key === countryKey
    })

    return {
        country: country?.name,
        province: names[0] || '',
        city: names[1] || '',
        dist: names[2] || '',
        address: addressObj.address || addressObj.adAddress || ''
    }
}